package com.powernobug.service.impl;

import com.powernobug.bean.model.MarketSystem;
import com.powernobug.bean.model.MarketSystemExample;
import com.powernobug.mapper.MarketSystemMapper;
import com.powernobug.service.ConfigService;
import com.powernobug.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConfigServiceImpl implements ConfigService {
    @Override
    public Map<String, String> mallQuery() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            MarketSystemMapper systemMapper = sqlSession.getMapper(MarketSystemMapper.class);
            // where key_name like ?
            // market_mall_%
            MarketSystemExample example = new MarketSystemExample();
            example.createCriteria().andKeyNameLike("market_mall_%");
            List<MarketSystem> marketSystems = systemMapper.selectByExample(example);

            /*Map<String, String> dataMap = new HashMap<>();
            for (MarketSystem marketSystem : marketSystems) {
                dataMap.put(marketSystem.getKeyName(), marketSystem.getKeyValue());
            }*/
            Map<String, String> dataMap = marketSystems.stream()
                    .collect(Collectors.toMap(MarketSystem::getKeyName, MarketSystem::getKeyValue));
            return dataMap;
        }
    }

    @Override
    public void update(Map<String, String> parameterMap) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            MarketSystemMapper systemMapper = sqlSession.getMapper(MarketSystemMapper.class);
            // update market_system set key_value = ? where key_name = ?
            
            // 更新多次
            Iterator<String> iterator = parameterMap.keySet().iterator(); // 根据 Map的key来进行遍历
            while (iterator.hasNext()) {
                String keyName = iterator.next();
                String keyValue = parameterMap.get(keyName);

                /*
                MarketSystem marketSystem = new MarketSystem();
                marketSystem.setKeyValue(keyValue);
                MarketSystemExample example = new MarketSystemExample();
                example.createCriteria().andKeyNameEqualTo(keyName);
                int affectedRows = systemMapper.updateByExampleSelective(marketSystem, example);
                */
                
                systemMapper.updateByKeyName(keyName, keyValue);
            }
            sqlSession.commit();
        }

    }
}
